﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using LitJson;
using SangsTools;

namespace Player
{
    public class Shop
    {
        private const string TBLPath = "Addressable/TBL", AddressableName = "ShopData";

        private IShopItemRandomer randomer;
        private float _fLastRefreshTime = 0;
        public STShopData ShopData { get; private set; }

        public float RefreshCD => Mathf.Max(0, _fLastRefreshTime + (float)ShopData.fRefreshTime - Time.time);
        public bool NeedRefresh => RefreshCD <= 0;

        private List<STShopItemData> _listItemData;
        public STShopItemData[] ShopItemData
        {
            get
            {
                if (NeedRefresh)
                    RefreshItemList();
                return _listItemData.ToArray();
            }
        }

        public Shop()
        {
            _listItemData = new List<STShopItemData>();
            _fLastRefreshTime = -9999;//保证第一次获取就能刷新
        }

        public async Task InitAsync()
        {
            TextAsset textAsset = await Addressables.LoadAssetAsync<TextAsset>(AddressableName).Task;
            if (textAsset != null && !string.IsNullOrEmpty(textAsset.text))
            {
                try
                {
                    ShopData = JsonMapper.ToObject<STShopData>(textAsset.text);
                }
                catch
                {
                    throw new Exception("-商店-信息表数据异常");
                }
            }
            else
                throw new Exception("-商店-道具信息表加载失败");

            randomer = new NormalShopItemRandomer(ShopData);
        }

        public void Reset()
        {
            RefreshItemList();
        }

        public void RefreshItemList()
        {
            _fLastRefreshTime = Time.time;

            _listItemData.Clear();
            _listItemData.AddRange(randomer.GetRandomItemList());
        }

        public bool BuyItem(int index)
        {
            //索引越界判定
            if (_listItemData == null || _listItemData.Count <= index || index < 0) return false;
            //是否待售判定
            STShopItemData shopItemData = _listItemData[index];
            if (shopItemData.bSold) return false;
            //判定价格
            if (MyPlayer.Ins.MyBackpack.Gold < shopItemData.nPrice) return false;
            //先钱
            MyPlayer.Ins.MyBackpack.Gold -= shopItemData.nPrice;
            //后货
            GetItem(shopItemData);
            //改标记
            shopItemData.bSold = true;
            _listItemData[index] = shopItemData;
            return true;
        }

        private void GetItem(STShopItemData shopItemData)
        {
            switch (shopItemData.emItemType)
            {
                case EMShopItemType.Item:
                    MyPlayer.Ins.MyBackpack.GetItem(shopItemData.strItemTag,shopItemData.nCount);
                    break;
                case EMShopItemType.Science:
                    MyPlayer.Ins.MyScience.ScienceNum += shopItemData.nCount;
                    break;
                case EMShopItemType.Buff:
                    break;
                default:
                    break;
            }
        }

#if UNITY_EDITOR
        public static void SaveTBLData()
        {
            string json = LitJson.JsonMapper.ToJson(GetShopData());
            //Debug.Log(json.ToUTF8());
            SangsTools.MyJsonTools.SaveJsonFile(json.ToUTF8(), TBLPath, AddressableName);
        }
        private static STShopData GetShopData()
        {
            return new STShopData()
            {
                nBasePrice=100,
                fGoldToScienceCoefficient=0.1f,
                fPriceIncrease=1.2f,
                fRefreshTime=60f,
            };
        }
#endif

    }
}
